<template>
  <div>
    <div class="wrap" v-loading="loading">

      <el-card class="header-card">
        <div class="item">
          <p class="font-bold">采购单号：{{procureNo}}</p>
          <p>制单时间：{{createTime}}</p>
        </div>
      </el-card>

      <div class="content">
        <template v-if="tableData.length > 0">
          <h3>批发采购</h3>
          <div class="table">
            <el-table
              ref="previewOrder"
              row-key="orderId"
              :data="tableData"
              :span-method="objectSpanMethod1"
              border
            >
              <el-table-column
                prop="orderId"
                label="Mercado 订单号"
                align="center"
                min-width="180"
              >
                <template slot-scope="{row}">
                  <el-link
                    :underline="false"
                    v-for="orderId in row.orderIds"
                    :key="orderId"
                    @click="jumpOrderInfo(orderId)"
                  >
                    {{orderId}}
                  </el-link>

                </template>
              </el-table-column>

              <el-table-column
                prop="goodsImage"
                label="封面"
                align="center"
                width="120"
              >
                <template slot-scope="{row}">
                  <img :src="row.goods.image" width="85px" alt="">
                </template>
              </el-table-column>

              <el-table-column
                prop="goodsTitle"
                label="标题"
                align="left"
                min-width="300"
              >
                <template slot-scope="{row}">
                  <el-tooltip class="item" effect="dark" :content="row.goods.title" placement="top">
                    <div class="goods-title hidden-2">
                      {{row.goods.title}}
                    </div>
                  </el-tooltip>

                  <div class="goods-SKU-info hidden-1" v-if="row.goods.attributes.length > 0">
                  <span
                    v-for="attr in row.goods.attributes"
                    :key="attr.name"
                    class="attr"
                  >
                    {{attr.name}} : {{attr.value}}
                    <span class="attr-link"> | </span>
                  </span>
                  </div>
                </template>
              </el-table-column>

              <el-table-column
                prop="goodsId"
                label="适用Listing ID与SKU"
                align="center"
                min-width="200"
              >
                <template slot-scope="{row}">
                  <p
                    v-for="item in row.goods.goodsList"
                    :key="item.id"
                    style="margin: 0"
                  >
                    {{item.goodsId}} {{item.sku ? `(${item.sku})` : ''}}
                  </p>
                </template>
              </el-table-column>

              <el-table-column
                prop="orderNum"
                label="订单需求量"
                align="center"
                min-width="100"
              >
              </el-table-column>

              <el-table-column
                prop="packageType"
                label="包装服务"
                align="center"
                width="120"
              >
                <template slot-scope="{row}">
                  <template v-if="row.packageType">
                    <el-tag type="danger" style="font-size: 13px">
                      {{ getPackageTypeStr(row.packageType)}}
                    </el-tag>
                    <br>

                  </template>
                  <el-link type="primary" :underline="false" style="font-size: 13px" @click="showPackageDialog(row)">{{row.packageType ? '修改' : '选择服务'}}</el-link>
                </template>
              </el-table-column>

              <el-table-column
                prop="supplierLoginId"
                label="供应商"
                align="center"
                min-width="150"
                show-overflow-tooltip
              >
                <template slot-scope="{row}">
                  {{row.aliGoods ? row.aliGoods.supplierLoginId : '-'}}
                  <template v-if="row.aliGoods">
                    <br>
                    <supplier-relation-tag :supplier-relation="row.aliGoods.supplierRelation"></supplier-relation-tag>
                  </template>
                </template>
              </el-table-column>

              <el-table-column
                prop="aliGoods"
                label="采购货源"
                align="left"
                min-width="300"
              >
                <template slot-scope="{row}">
                  <ali-goods :ali-goods="row.aliGoods"></ali-goods>
                </template>
              </el-table-column>
              <el-table-column
                prop="minOrderQuantity"
                label="起批量"
                align="center"
                min-width="100"
              >
                <template slot-scope="{row}">
                  <template v-if="!row.aliGoods">-</template>
                  <template v-else>
                    <div>
                      {{row.aliGoods.minOrderQuantity}}{{row.aliGoods.unit}}起批
                    </div>
                    <div v-if="row.aliGoods.mixWholeSale === 1">
                      {{row.aliGoods.mixNumber}}{{row.aliGoods.unit}}混批
                    </div>
                    <div v-if="row.aliGoods.isConsignMarketOffer">
                      一件代发
                    </div>

                  </template>
                </template>
              </el-table-column>
              <el-table-column
                prop="goodsNum"
                label="本次采购数量"
                align="center"
                min-width="150"
              >
                <template slot-scope="{row}">
                <span :class="{
                  'font-red': row.previewOrderData && row.previewOrderData.isQuantityGoods === 1
                }">{{row.previewOrderData ? row.previewOrderData.quantity : '-'}}</span>
                  <br>

                  <template v-if="row.previewOrderData && row.previewOrderData.isQuantityGoods === 1">
                    <el-tooltip class="item" effect="dark" content="Top Center 提示文字" placement="top">
                      <template slot="content">
                        <div style="width: 400px;font-size: 13px">
                          <p>当前商品订单需求量未满足采购货源的起批量要求，本次采购数量默认增加到起批量要求。</p>
                          <p>您仍可继续采购，确认采购后，未达起批量要求的商品将拆分为新的采购单，请自行前往1688联系供应商修改价格后再操作付款拆分后的采购单</p>
                          <p>如当前商品支持一件代发，你也可以通过右侧操作按钮切换为“一件代发采购”进行采购。</p>
                        </div>
                      </template>
                      <el-tag
                        effect="dark"
                        type="danger"
                      >
                        <i class="el-icon-warning-outline"></i>
                        未达起批量要求
                      </el-tag>
                    </el-tooltip>
                  </template>
                </template>
              </el-table-column>
              <el-table-column
                prop="finalUnitPrice"
                label="商品单价（元）"
                align="center"
                min-width="120"
              >
                <template slot-scope="{row}">
                  <span>{{row.previewOrderData ? row.previewOrderData.finalUnitPrice : '-'}}</span>
                </template>
              </el-table-column>
              <el-table-column
                prop="amount"
                label="商品总额（元）"
                align="center"
                min-width="120"
              >
                <template slot-scope="{row}">
                  <span>{{row.previewOrderData ? row.previewOrderData.amount : '-'}}</span>
                </template>
              </el-table-column>
              <el-table-column
                prop="sumCarriage"
                label="运费（元）"
                align="center"
                min-width="120"
              >
                <template slot-scope="{row}">
                  <span>{{row.previewOrderData ? row.previewOrderData.sumCarriage : '-'}}</span>
                </template>
              </el-table-column>
              <el-table-column
                prop="shopPromotion"
                label="优惠金额（元）"
                align="center"
                min-width="120"
              >
                <template slot-scope="{row}">
                  <span>{{row.previewOrderData ? (row.previewOrderData.shopPromotion > 0 ? '-' + row.previewOrderData.shopPromotion : row.previewOrderData.shopPromotion) : '-'}}</span>
                </template>
              </el-table-column>
              <el-table-column
                prop="sumPayment"
                label="总额（元）"
                align="center"
                min-width="120"
              >
                <template slot-scope="{row}">
                  <span>{{row.previewOrderData ? row.previewOrderData.sumPayment : '-'}}</span>
                </template>
              </el-table-column>
              <el-table-column
                prop="operate"
                label="操作"
                align="left"
                min-width="350"
              >
                <template slot-scope="{row}">
                  <setting-procure :suit-id="row.goods.suitId" @changeProcure="getPreviewOrder" class="mgr10"></setting-procure>
                  <el-button
                    type="warning"
                    @click="fenxiaoOrder(row)"
                    class=""
                    v-if="row.aliGoods"
                  >一件代发采购</el-button>
                  <el-button type="danger" @click="removeOrderId(row)" v-if="info.goodsNum > 1">删除</el-button>
                </template>
              </el-table-column>

            </el-table>
          </div>
        </template>

        <template v-if="fxTableData.length > 0">
          <h3>一件代发采购</h3>

          <el-table
            row-key="orderId"
            :data="fxTableData"
            :span-method="objectSpanMethod2"
            border
          >

            <el-table-column
              prop="orderId"
              label="Mercado 订单号"
              align="center"
              min-width="180"
            >
              <template slot-scope="{row}">
                <el-link
                  :underline="false"
                  v-for="orderId in row.orderIds"
                  :key="orderId"
                  @click="jumpOrderInfo(orderId)"
                >
                  {{orderId}}
                </el-link>

              </template>
            </el-table-column>

            <el-table-column
              prop="goodsImage"
              label="封面"
              align="center"
              width="120"
            >
              <template slot-scope="{row}">
                <img :src="row.goods.image" width="85px" alt="">
              </template>
            </el-table-column>

            <el-table-column
              prop="goodsTitle"
              label="标题"
              align="left"
              min-width="300"
            >
              <template slot-scope="{row}">
                <el-tooltip class="item" effect="dark" :content="row.goods.title" placement="top">
                  <div class="goods-title hidden-2">
                    {{row.goods.title}}
                  </div>
                </el-tooltip>

                <div class="goods-SKU-info hidden-1" v-if="row.goods.attributes.length > 0">
                  <span
                    v-for="attr in row.goods.attributes"
                    :key="attr.name"
                    class="attr"
                  >
                    {{attr.name}} : {{attr.value}}
                    <span class="attr-link"> | </span>
                  </span>
                </div>
              </template>
            </el-table-column>

            <el-table-column
              prop="goodsId"
              label="适用Listing ID与SKU"
              align="center"
              min-width="200"
            >
              <template slot-scope="{row}">
                <p
                  v-for="item in row.goods.goodsList"
                  :key="item.id"
                  style="margin: 0"
                >
                  {{item.goodsId}} {{item.sku ? `(${item.sku})` : ''}}
                </p>
              </template>
            </el-table-column>

            <el-table-column
              prop="orderNum"
              label="订单需求量"
              align="center"
              min-width="100"
            >
            </el-table-column>

            <el-table-column
              prop="packageType"
              label="包装服务"
              align="center"
              width="120"
            >
              <template slot-scope="{row}">
                <template v-if="row.packageType">
                  <el-tag type="danger" style="font-size: 13px">
                    {{ getPackageTypeStr(row.packageType)}}
                  </el-tag>
                  <br>

                </template>
                <el-link type="primary" :underline="false" style="font-size: 13px" @click="showPackageDialog(row)">{{row.packageType ? '修改' : '选择服务'}}</el-link>
              </template>
            </el-table-column>

            <el-table-column
              prop="supplierLoginId"
              label="供应商"
              align="center"
              min-width="150"
              show-overflow-tooltip
            >
              <template slot-scope="{row}">
                {{row.aliGoods ? row.aliGoods.supplierLoginId : '-'}}
                <template v-if="row.aliGoods">
                  <br>
                  <supplier-relation-tag :supplier-relation="row.aliGoods.supplierRelation"></supplier-relation-tag>
                </template>
              </template>
            </el-table-column>

            <el-table-column
              prop="aliGoods"
              label="采购货源"
              align="left"
              min-width="300"
            >
              <template slot-scope="{row}">
                <ali-goods :ali-goods="row.aliGoods"></ali-goods>
              </template>
            </el-table-column>
            <el-table-column
              prop="minOrderQuantity"
              label="起批量"
              align="center"
              min-width="100"
            >
              <template slot-scope="{row}">
                <template v-if="!row.aliGoods">-</template>
                <template v-else>
                  <div>
                    {{row.aliGoods.minOrderQuantity}}{{row.aliGoods.unit}}起批
                  </div>
                  <div v-if="row.aliGoods.mixWholeSale === 1">
                    {{row.aliGoods.mixNumber}}{{row.aliGoods.unit}}混批
                  </div>
                  <div v-if="row.aliGoods.isConsignMarketOffer">
                    一件代发
                  </div>

                </template>
              </template>
            </el-table-column>
            <el-table-column
              prop="goodsNum"
              label="本次采购数量"
              align="center"
              min-width="150"
            >
              <template slot-scope="{row}">
                <span :class="{
                  'font-red': row.previewOrderData && row.previewOrderData.isQuantityGoods === 1
                }">{{row.previewOrderData ? row.previewOrderData.quantity : '-'}}</span>
                <br>

                <template v-if="row.previewOrderData && row.previewOrderData.isQuantityGoods === 1">
                  <el-tooltip class="item" effect="dark" content="Top Center 提示文字" placement="top">
                    <template slot="content">
                      <div style="width: 400px;font-size: 13px">
                        <p>当前商品订单需求量未满足采购货源的起批量要求，本次采购数量默认增加到起批量要求。</p>
                        <p>您仍可继续采购，确认采购后，未达起批量要求的商品将拆分为新的采购单，请自行前往1688联系供应商修改价格后再操作付款拆分后的采购单</p>
                        <p>如当前商品支持一件代发，你也可以通过右侧操作按钮切换为“一件代发采购”进行采购。</p>
                      </div>
                    </template>
                    <el-tag
                      effect="dark"
                      type="danger"
                    >
                      <i class="el-icon-warning-outline"></i>
                      未达起批量要求
                    </el-tag>
                  </el-tooltip>
                </template>
              </template>
            </el-table-column>
            <el-table-column
              prop="finalUnitPrice"
              label="商品单价（元）"
              align="center"
              min-width="120"
            >
              <template slot-scope="{row}">
                <span>{{row.previewOrderData ? row.previewOrderData.finalUnitPrice : '-'}}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="amount"
              label="商品总额（元）"
              align="center"
              min-width="120"
            >
              <template slot-scope="{row}">
                <span>{{row.previewOrderData ? row.previewOrderData.amount : '-'}}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="sumCarriage"
              label="运费（元）"
              align="center"
              min-width="120"
            >
              <template slot-scope="{row}">
                <span>{{row.previewOrderData ? row.previewOrderData.sumCarriage : '-'}}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="shopPromotion"
              label="优惠金额（元）"
              align="center"
              min-width="120"
            >
              <template slot-scope="{row}">
                <span>{{row.previewOrderData ? (row.previewOrderData.shopPromotion > 0 ? '-' + row.previewOrderData.shopPromotion : row.previewOrderData.shopPromotion) : '-'}}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="sumPayment"
              label="总额（元）"
              align="center"
              min-width="120"
            >
              <template slot-scope="{row}">
                <span>{{row.previewOrderData ? row.previewOrderData.sumPayment : '-'}}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="operate"
              label="操作"
              align="left"
              min-width="350"
            >
              <template slot-scope="{row}">
                <setting-procure :suit-id="row.goods.suitId" @changeProcure="getPreviewOrder" class="mgr10"></setting-procure>
                <el-button type="warning" @click="pifaOrder(row)" class="">批发采购</el-button>
                <el-button type="danger" @click="removeOrderId(row)" v-if="info.goodsNum > 1">删除</el-button>
              </template>
            </el-table-column>

          </el-table>

        </template>



        <div class="card">
          <el-card class="footer-card">
            <div class="item">
              <p class="text1">商品金额：<span class="font-bold">{{info.sumGoodsPayment}} 元</span></p>
              <p class="text1">运费金额：<span class="font-bold">{{ info.sumCarriage }} 元</span></p>
              <p class="text1">优惠金额：<span class="font-bold">{{ info.sumPromotion }} 元</span></p>
              <p class="text2" style="margin-bottom: 30px">总计：<span class="font-bold font-red">{{ info.sumPayment }} 元</span></p>
              <p class="text1 font-red">
                采购的商品将直接发货到仓库，待管理员签收后清点确认后贴单入库
              </p>
              <p class="text1 font-red">
                未达起批量要求的商品本次采购数量默认增加到起批量要求，确认采购后将拆分为新的采购单，请自行前往请自行前往1688联系供应商修改价格后再操作付款
              </p>
            </div>
          </el-card>
        </div>


        <div class="footer" :style="{
          top:fixedTopHeight,
        }">
          <div class="left">
            本次采购 <span class="font-red">{{info.goodsKindOfNum}}</span> 种商品，共计<span class="font-red">{{info.goodsNum}}</span>件;
            <template v-if="info.expiredGoodsNum > 0">
              未配置货源商品<span class="font-red">{{info.expiredGoodsNum}}</span>种;
            </template>
            <template v-if="info.minOrderQuantityGoodsNum > 0">
              未达起批量要求商品<span class="font-red">{{info.minOrderQuantityGoodsNum}}</span>种;
            </template>
          </div>
          <div class="right">
            <el-button @click="backOrderList">返回</el-button>
            <el-button type="danger" @click="cancelProcure" :loading="createOrderLoading">取消采购</el-button>
            <el-button type="primary" @click="createOrder" :loading="createOrderLoading">确认采购</el-button>
          </div>
        </div>
      </div>

    </div>

    <el-dialog
      title="确认采购？"
      :visible.sync="createOrderDialog"
      width="40%"
    >
      <div class="createOrderDialog">
        <template v-if="quantityGoodsNum > 0 && info.expiredGoodsNum === 0 && info.successOrderNum > 0">
          <div class="title">当前采购单存在<span class="foot-tips">{{ quantityGoodsNum }}</span>种未达起批量要求的商品，确认采购后将拆分为两张采购单：</div>
        </template>
        <template v-if="quantityGoodsNum === 0 && info.expiredGoodsNum > 0 && info.successOrderNum > 0">
          <div class="title">当前采购单存在<span class="foot-tips">{{ info.expiredGoodsNum }}</span>种尚未配置采购货源的商品，确认采购后将拆分两张采购单：</div>
        </template>
        <template v-if="quantityGoodsNum > 0 && info.expiredGoodsNum > 0 && info.successOrderNum > 0">
          <div class="title">当前采购单存在<span class="font-tips">{{ info.expiredGoodsNum }}</span>种尚未配置采购货源和<span class="font-tips">{{ quantityGoodsNum }}</span>种未达起批量要求的商品，确认采购后将拆分三张采购单：</div>
        </template>
        <template v-if="quantityGoodsNum > 0 && info.expiredGoodsNum === 0 && info.successOrderNum === 0">
          <div class="title">当前采购单存在<span class="foot-tips">{{ quantityGoodsNum }}</span>种未达起批量要求的商品，确认继续采购吗</div>
        </template>
        <template v-else-if="quantityGoodsNum > 0 && info.expiredGoodsNum > 0 && info.successOrderNum === 0">
          <div class="title">当前采购单存在<span class="foot-tips">{{ info.expiredGoodsNum }}</span>种尚未配置采购货源和<span class="foot-tips">{{ quantityGoodsNum }}</span>种未达起批量要求的商品，确认采购后将拆分两张采购单:</div>
        </template>
        <template v-if="(quantityGoodsNum > 0 || info.expiredGoodsNum > 0) && !(quantityGoodsNum > 0 && info.expiredGoodsNum === 0 && info.successOrderNum === 0)"></template>
        <div class="item">
          <p v-if="successGoodsNum > 0">采购单-1：已配置采购货源且不存在未达起批量要求的商品的采购单</p>
          <p v-if="quantityGoodsNum > 0">采购单-2：未达起批量要求的商品生成的采购单</p>
          <p v-if="info.expiredGoodsNum > 0">采购单-3：未配置采购货源的商品生成的采购单</p>
        </div>

        <template v-if="quantityGoodsNum > 0 && info.expiredGoodsNum === 0 && info.successOrderNum > 0">
          <div class="">拆分后后您可以先完成支付采购单-1，再配置处理采购单-2</div>
        </template>
        <template v-else-if="quantityGoodsNum === 0 && info.expiredGoodsNum > 0 && info.successOrderNum > 0">
          <div class="">拆分后您可以先完成支付采购单-1，再配置处理采购单-3</div>
        </template>
        <template v-else-if="quantityGoodsNum > 0 && info.expiredGoodsNum > 0 && info.successOrderNum > 0">
          <div class="">拆分后您可以先完成支付采购单-1，再配置处理采购单-2、采购单-3</div>
        </template>
        <template v-else-if="quantityGoodsNum > 0 && info.expiredGoodsNum > 0 && info.successOrderNum === 0">
          <div class="">拆分后您可以先完成支付采购单-2，再配置处理采购单-3</div>
        </template>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="createOrderDialog = false">取 消</el-button>
        <el-button type="primary" @click="sureCreateOrder" :loading="createOrderLoading">确 定</el-button>
      </span>
    </el-dialog>


    <el-dialog
      title="包装服务"
      :visible.sync="packageDialog"
    >
      <el-form :model="packageForm" label-width="150px">
        <el-form-item label="包装服务">
          <sticker-package v-model="packageForm.packageType" :package-type="packageForm.packageType"></sticker-package>
        </el-form-item>
        <el-form-item label="预计代贴单费用">
          <div style="color: #ED6A0C;font-size: 16px">{{ calStickerPrice }} 元</div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="packageDialog = false">取 消</el-button>
        <el-button type="primary" @click="submitPackageForm">确 定</el-button>
      </div>
    </el-dialog>


    <el-dialog
      title="提示"
      :visible.sync="fenxiaoTips1Dialog"
      width="500px"
      class="fenxiao-tips"
    >
      <div>非常抱歉，当前商品不支持一件代发，如需继续使用该功能，建议您重新配置采购货源再尝试当前操作。</div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="fenxiaoTips1Dialog = false">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="提示"
      :visible.sync="fenxiaoTips2Dialog"
      width="500px"
      class="fenxiao-tips"
    >
      <div>您尚未加盟成为该供应商的分销商，无法使用该功能。如需使用一件代发采购，请参考

        <span style="color: #4A9FF9;cursor: pointer" @click="jumpProcureHelp">《使用教程》</span>
        前往1688操作加盟后返回当前页刷新后再操作。</div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="fenxiaoTips2Dialog = false">取 消</el-button>
        <el-button type="primary" @click="jumpProcureHelp">查看教程</el-button>
      </span>
    </el-dialog>

  </div>

</template>

<script>
import {
  cancelProcure,
  createProcureOrder,
  getPreviewOrder,
  getProcureOrderPreviewOrder,
  removeProcureOrderId
} from "@/api/procure";
import {jumpLink, jumpProcureHelp} from "@/utils/common";
import {deepCopy} from "@/utils";
import SettingProcure from "@/views/procure/components/settingProcure.vue";
import AliGoods from "@/views/procure/components/aliGoods.vue";
import {getPackageTypeStr} from "@/utils/order";
import SupplierRelationTag from "@/views/procure/components/supplierRelationTag";
import StickerPackage from "@/views/order/components/stickerPackage";

export default {
  name: "procureOrderPreviewOrder",
  components: {StickerPackage, SupplierRelationTag, AliGoods, SettingProcure},
  data(){
    return {
      orderIds: [],
      loading: false,
      data: [],
      info:{
        goodsKindOfNum: 0, // 数量种类数
        goodsNum: 0, // 下单商品数
        minOrderQuantityGoodsNum: 0, // 不符合起订量
        settingGoodsNum: 0, // 已经设置的商品数
        sumCarriage: 0, // 总运费
        sumPayment: 0, // 总订单金额
        sumPromotion: 0, // 总优惠价格
        sumGoodsPayment: 0, // 总优惠价格
        successOrderNum: 0, // 能够正常下单的订单数
        expiredGoodsNum: 0, // 未配置或失效的商品数量
      },
      createOrderDialog: false,
      successGoodsNum: 0, // 正常的商品数（不一定是订单数）
      quantityGoodsNum: 0, // 起批数要更改的数量
      settingGoodsNum: 0, // 需要配置商品的数量
      createOrderLoading: false,
      deleteLoading: false,
      procureNo: '',
      createTime: '',
      fixedTopHeight: '0',
      fxTableData: [],
      fxOrderIds: [],
      packageDialog: false,
      packageForm: {
        packageType: '',
        orderObj: {},
      },
      getPackageTypeStr,
      tableData: [],
      fenxiaoTips1Dialog: false,
      fenxiaoTips2Dialog: false,
    }
  },
  computed:{
    // 计算单元格合并
    mergeCell(){
      const mergeObj = {}; // 用来记录需要合并行的下标
      const mergeArr = [
        'orderId', // 订单id
        'goodsImage',  // 封面
        'goodsId', // listing
        'goodsTitle',  // 标题
        'orderNum', // 订单需求量
        'aliGoods', // 采购货源
        'minOrderQuantity', // 最低采购量
        'goodsNum', // 本次采购量
        'finalUnitPrice', // 采购的商品单价
        'amount', // 商品的总价
        'sumCarriage', // 运费
        'sumPayment', // 总费用
        'supplierLoginId', // 总费用
        'shopPromotion',
        'operate',
      ]; // 表格中的列名

      // 根据suitId合并的字段
      const suitMergeArr = [
        'orderId', // 订单id
        'goodsImage',  // 封面
        'goodsId', // listing
        'goodsTitle',  // 标题
        'orderNum', // 订单需求量
        'aliGoods', // 采购货源
        'minOrderQuantity', // 最低采购量
        'goodsNum', // 本次采购量
        'finalUnitPrice', // 采购的商品单价
        'amount', // 商品的总价
        'operate',
      ];

      // 根据供应商合并的字段
      const supplierArr = [
        'sumCarriage', // 运费
        'sumPayment', // 总费用
        'shopPromotion',
        'supplierLoginId', // 供应商
      ];

      mergeArr.forEach(key=>{
        mergeObj[key] = [1];
      })
      let suitIdKey = 0;
      let supplierKey = 0;
      this.tableData.forEach((item,index)=>{
        // 第一列数据不处理
        if(index === 0){
          return;
        }
        // 根据suit_id 合并
        if(item.goods.suitId === this.tableData[index - 1].goods.suitId){
          suitMergeArr.forEach(key=>{
            mergeObj[key][suitIdKey] += 1;
            mergeObj[key].push(0); // 添加一个0 站位
          })
        }else{
          suitIdKey = index; // 记录当前行
          suitMergeArr.forEach(key=>{
            mergeObj[key].push(1); // 添加一个1
          })
        }

        // 根据供应商id 合并
        if(item.aliGoods && this.tableData[index - 1].aliGoods &&
          item.aliGoods.supplierLoginId && this.tableData[index - 1].aliGoods.supplierLoginId &&
          item.aliGoods.supplierLoginId === this.tableData[index - 1].aliGoods.supplierLoginId
        ){
          supplierArr.forEach(key=>{
            mergeObj[key][supplierKey] += 1;
            mergeObj[key].push(0); // 添加一个0 站位
          })
        }else{
          supplierKey = index; // 记录当前行
          supplierArr.forEach(key=>{
            mergeObj[key].push(1); // 添加一个1
          })
        }
      })

      return mergeObj
    },
    // 计算贴单
    calStickerPrice(){
      let sumPrice = 0;
      if(this.packageForm.orderObj.orderIds){
        this.packageForm.orderObj.orderIds.forEach( orderId =>{
          this.data.find(item => {
            if(item.orderId === orderId){
              switch (item.siteId){
                case 'MLM': // 墨西哥
                  sumPrice = this.$cal.accAdd(sumPrice,this.$store.getters.MLMPrice)
                  break;
                case 'MLB':
                  sumPrice = this.$cal.accAdd(sumPrice,this.$store.getters.MLBPrice)
                  break;
                case 'MLC':
                  sumPrice = this.$cal.accAdd(sumPrice,this.$store.getters.MLCPrice)
                  break;
                case 'MCO':
                  sumPrice = this.$cal.accAdd(sumPrice,this.$store.getters.MCOPrice)
                  break;
              }
              return true;
            }
          })
        })
      }

      const orderNum = this.packageForm.orderObj.orderIds ? this.packageForm.orderObj.orderIds.length : 1;
      let packagePrice = 0; //包装服务费
      switch (this.packageForm.packageType){
        case 'vacuum': // 真空
          packagePrice = this.$cal.accMul(orderNum,this.$store.getters.vacuum)
          break;
        case 'leatheroid': // 纸皮
          packagePrice = this.$cal.accMul(orderNum,this.$store.getters.leatheroid)
          break;
        case 'special': // 特殊
          packagePrice = this.$cal.accMul(orderNum,this.$store.getters.special)
          break;
      }

      sumPrice = this.$cal.accAdd(sumPrice,packagePrice)
      return sumPrice;
    }
  },
  created() {
    window.addEventListener("scroll", this.fixedTopHeightFunc);
    this.fixedTopHeightFunc()
    if(!this.$route.query.procureNo){
      this.$errorMessage('参数缺失')
      this.$router.go(-1)
      return;
    }
    this.procureNo = this.$route.query.procureNo;

    if(typeof this.$route.query.fxOrderIds === 'string'){
      this.fxOrderIds = [this.$route.query.fxOrderIds]
    }else{
      if(this.$route.query.fxOrderIds){
        this.fxOrderIds = [...this.$route.query.fxOrderIds]
      }
    }

    this.getPreviewOrder()
  },
  methods:{
    jumpProcureHelp,
    jumpLink,
    // 获取预览订单数据
    getPreviewOrder(){
      this.loading = true
      const params = {
        procureNo: this.procureNo,
        fxOrderIds: this.fxOrderIds,
      }
      getProcureOrderPreviewOrder(
        params
      )
        .then(res=>{
          this.loading = false
          if(res.error === 0){
            // 处理数据
            this.tableData = this.formatTableData(res.data)
            this.fxTableData = this.formatTableData(res.info.fxData)
            this.data = [...this.tableData,...this.fxTableData]

            this.info.goodsKindOfNum = res.info.goodsKindOfNum
            this.info.goodsNum = res.info.goodsNum
            this.info.minOrderQuantityGoodsNum = res.info.minOrderQuantityGoodsNum
            this.info.settingGoodsNum = res.info.settingGoodsNum
            this.info.sumCarriage = res.info.sumCarriage
            this.info.sumPayment = res.info.sumPayment
            this.info.sumPromotion = res.info.sumPromotion
            this.info.sumGoodsPayment = res.info.sumGoodsPayment
            this.info.successOrderNum = res.info.successOrderNum
            this.info.expiredGoodsNum = res.info.expiredGoodsNum
            this.createTime = res.info.createTime
          }else{
            this.$errorMessage(res.message)
            if(res.error === 202){
              this.$router.go(-1);
            }
          }
        })
    },
    objectSpanMethod1({ row, column, rowIndex, columnIndex }) {
      const mergeCell = this.calMergeCell(this.tableData)
      if(mergeCell[column.property]){
        if(mergeCell[column.property][rowIndex]) {
          return [mergeCell[column.property][rowIndex], 1]
        } else {
          // 如果为0则为需要合并的行
          return [0, 0];
        }
      }
    },
    objectSpanMethod2({ row, column, rowIndex, columnIndex }) {
      const mergeCell = this.calMergeCell(this.fxTableData)
      if(mergeCell[column.property]){
        if(mergeCell[column.property][rowIndex]) {
          return [mergeCell[column.property][rowIndex], 1]
        } else {
          // 如果为0则为需要合并的行
          return [0, 0];
        }
      }
    },
    // 更改配货源 重新刷新当前数据

    // 删除该条数据
    removeOrderId(row){

      this.$confirm('确定要删除该条数据吗', {
        confirmButtonText: '确定',
        cancelButtonClass: '取消'
      })
        .then(res=>{
          this.deleteLoading = true
          removeProcureOrderId({
            orderIds: row.orderIds
          })
            .then(res=>{
              this.deleteLoading = false
              if(res.error === 0){
                this.$successMessage('删除成功')
                this.getPreviewOrder()
              }
            })


        })
        .catch(res=>{
          // 点击了取消
        });
    },
    // 返回订单列表页
    backOrderList(){
      this.$router.push({
        name: 'orderList'
      })
    },
    // 数据格式
    formatTableData(data){
      const tableData = [];
      data.forEach(item=>{
        const orderIds = [];
        let orderNum = 0; // 订单需求量
        data.forEach(_item=>{
          // 没有对应的阿里商品
          if(_item.goods.suitId === item.goods.suitId){
            orderIds.push(_item.orderId)
            orderNum += 1;
          }
        })
        const obj = deepCopy(item);
        obj.orderIds = orderIds
        obj.orderNum = orderNum
        obj.packageType = obj.packageType || '';
        tableData.push(obj);
      })
      return tableData;
    },
    // 下单
    createOrder(){
      if(this.data.length === 0){
        this.$errorMessage('无订单数据');
        return;
      }
      this.successGoodsNum = 0;
      this.quantityGoodsNum = 0; // 起批数要更改的数量
      this.settingGoodsNum = 0; // 需要配置商品的数量
      this.data.forEach(item=>{
        if(!item.aliGoods || item.aliGoods.isExpired || !item.previewOrderData){
          this.settingGoodsNum +=1;
          return;
        }
        if(item.previewOrderData.isQuantityGoods === 1){
          this.quantityGoodsNum += 1;
          return;
        }
        this.successGoodsNum += 1;
      })

      // 所有商品都需要配置
      if(this.settingGoodsNum === this.data.length){
        this.$confirm('当前采购单所有商品未配置采购货源或采购货源已失效、无库存，无法下单采购','请先配置采购货源', {
          dangerouslyUseHTMLString: true,
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          showCancelButton: false,
        })
          .then(res=>{

          })
          .catch(res=>{
            // 点击了取消
          });
        return;
      }

      // 所有商品都是正常的
      if(this.successGoodsNum === this.data.length){
        this.sureCreateOrder()
        return;
      }else{
        this.createOrderDialog = true // 显示确认弹窗
      }
    },
    // 确定要提交订单
    sureCreateOrder(){
      this.createOrderLoading = true;
      this.$message('数据处理中...请勿刷新或关闭页面');
      // 包装服务
      const packageTypeArr = [];
      this.data.forEach(item=>{
        packageTypeArr.push({
          packageType: item.packageType,
          orderId: item.orderId
        })
      })

      const postData = {
        procureNo: this.procureNo,
        fxOrderIds: this.fxOrderIds,
        packageTypeArr: packageTypeArr,
      }
      createProcureOrder(postData)
        .then(res=>{
          this.createOrderLoading = false
          if(res.error !== 0){
            this.$errorMessage(res.message);
            return;
          }
          const procureOrderList = res.info.procureOrderList;
          // 先查询是否有type类型1的采购单 有则直接跳转
          let index = procureOrderList.findIndex(item=> item.type === 1)
          if(index !== -1){
            this.$router.push({
              name: 'procureOrderInfo',
              query: {
                procureNo: procureOrderList[index].procureNo,
              }
            })
            return;
          }

          index = procureOrderList.findIndex(item=> item.type === 2)
          if(index !== -1){
            this.$router.push({
              name: 'procureOrderInfo',
              query: {
                procureNo: procureOrderList[index].procureNo,
              }
            })
            return;
          }

          this.$router.push({
            name: 'procureOrderList',
          })

        })
    },
    // 取消采购
    cancelProcure(){
      this.createOrderLoading = true;
      cancelProcure({
        procureNo: this.procureNo,
      })
        .then(res=>{
          this.createOrderLoading = false;
          if(res.error === 0){
            this.$successMessage('操作成功');
            this.$router.push({
              name: 'procureOrderList'
            })
          }
        })
    },
    // 计算屏幕的高度
    fixedTopHeightFunc(){
      let windowH = window.innerHeight;
      let windowY = window.scrollY;

      this.fixedTopHeight = (windowH - 157 + windowY) + 'px';
    },
    // 刷新页面
    flushPage(){
      this.$router.push({
        name: 'procureOrderPreviewOrder',
        query: {
          procureNo: this.procureNo,
          fxOrderIds: this.fxOrderIds,
        }
      })
      this.getPreviewOrder()
    },
    // 展示包装服务的dialog
    showPackageDialog(row){
      this.packageForm.packageType = row.packageType;
      this.packageForm.orderObj = row;
      this.packageDialog = true;
      console.log(this.packageForm)
    },
    submitPackageForm(){
      this.packageForm.orderObj.orderIds.forEach(orderId=>{
        this.data.find(item => {
          if(item.orderId === orderId){
            item.packageType = this.packageForm.packageType
            return true;
          }
        })
      })
      this.packageDialog = false;
    },
    // 代发采购
    fenxiaoOrder(row){
      if(row.aliGoods.isConsignMarketOffer !== 1){
        this.fenxiaoTips1Dialog = true;
        return;
      }
      if(!row.aliGoods.supplierRelation){
        this.fenxiaoTips2Dialog = true;
        return;
      }
      row.orderIds.forEach(orderId => {
        if(this.fxOrderIds.findIndex(itemOrderId => orderId === itemOrderId) === -1){
          this.fxOrderIds.push(orderId)
        }
      })
      this.flushPage()
    },
    // 批发采购
    pifaOrder(row){
      row.orderIds.forEach(orderId => {
        const key = this.fxOrderIds.findIndex(itemOrderId => orderId === itemOrderId);
        if(key !== -1){
          this.fxOrderIds.splice(key,1)
        }
      })
      this.flushPage()
    },
    calMergeCell(tableData){
      const mergeObj = {}; // 用来记录需要合并行的下标

      // 根据suitId合并的字段
      const suitMergeArr = [
        'orderId', // 订单id
        'goodsImage',  // 封面
        'goodsId', // listing
        'goodsTitle',  // 标题
        'orderNum', // 订单需求量
        'operate',
      ];

      // 根据specId合并
      const specIdMergeArr = [
        'aliGoods', // 采购货源
        'minOrderQuantity', // 最低采购量
        'goodsNum', // 本次采购量
        'finalUnitPrice', // 采购的商品单价
        'amount', // 商品的总价
      ];

      // 根据供应商合并的字段
      const supplierArr = [
        'sumCarriage', // 运费
        'sumPayment', // 总费用
        'shopPromotion',
        'supplierLoginId', // 供应商
      ];

      suitMergeArr.forEach(key=>{
        mergeObj[key] = [1];
      })
      specIdMergeArr.forEach(key=>{
        mergeObj[key] = [1];
      })
      supplierArr.forEach(key=>{
        mergeObj[key] = [1];
      })
      let suitIdKey = 0;
      let supplierKey = 0;
      let specIdKey = 0;
      tableData.forEach((item,index)=>{
        // 第一列数据不处理
        if(index === 0){
          return;
        }
        // 根据suit_id 合并
        if(item.goods.suitId === tableData[index - 1].goods.suitId){
          suitMergeArr.forEach(key=>{
            mergeObj[key][suitIdKey] += 1;
            mergeObj[key].push(0); // 添加一个0 站位
          })
        }else{
          suitIdKey = index; // 记录当前行
          suitMergeArr.forEach(key=>{
            mergeObj[key].push(1); // 添加一个1
          })
        }

        // 根据供应商id 合并
        if(item.aliGoods && tableData[index - 1].aliGoods &&
          item.aliGoods.supplierLoginId && tableData[index - 1].aliGoods.supplierLoginId &&
          item.aliGoods.supplierLoginId === tableData[index - 1].aliGoods.supplierLoginId
        ){
          supplierArr.forEach(key=>{
            mergeObj[key][supplierKey] += 1;
            mergeObj[key].push(0); // 添加一个0 站位
          })
        }else{
          supplierKey = index; // 记录当前行
          supplierArr.forEach(key=>{
            mergeObj[key].push(1); // 添加一个1
          })
        }

        // 根据specId 合并
        if(item.specId && item.specId === tableData[index - 1].specId){
          specIdMergeArr.forEach(key=>{
            mergeObj[key][specIdKey] += 1;
            mergeObj[key].push(0); // 添加一个0 站位
          })
        }else{
          specIdKey = index;
          specIdMergeArr.forEach(key=>{
            mergeObj[key].push(1); // 添加一个1
          })
        }

      })

      return mergeObj
    },
    // 跳转到订单详情页
    jumpOrderInfo(orderId){
      const { href } = this.$router.resolve({
        name: 'orderInfo',
        query: {
          orderId: orderId
        }
      })
      window.open(href,'_blank')
    },
  }
}
</script>

<style scoped lang="less">
.wrap {
  padding: 10px 30px 80px;
  height: auto;
  min-height: 100vh;
  .header-card{
    margin-top: 10px;
    margin-bottom: 20px;
    font-size: 14px;
    background-color: rgba(242, 242, 242, 1);
    p{
      margin: 10px 0;
      padding: 0;
    }
    .font-bold{
      font-weight: bold;
    }
    .true-number{
      color: #FF0000;
      font-weight: 600;
    }
  }
  .header{
    display: flex;
    justify-content: space-between;
  }
  .content{

    .title{
      font-size: 14px;
      margin: 10px 0 ;
    }
  }
  .footer-card{
    text-align: right;
    background-color: rgba(242, 242, 242, 1);
    font-size: 14px;
    p{
      margin: 10px 0;
      padding: 0;
    }
    .text1{
      font-size: 13px;
      color: #767676;
    }
    .text2{
      font-size: 20px;
      color: #333333;
    }
    .font-bold{
      font-weight: 650;
    }
    .font-red{
      color: #FF0000;
    }
  }
}
.footer{
  height: 80px;
  //width: calc(100% - 60px);
  //position: absolute;
  line-height: 80px;
  margin-top: 30px;
  border-top: 1px solid #CCCCCC;
  //position: fixed;
  display: flex;
  justify-content: space-between;
  position: absolute;
  width: calc(100% - 60px);
  background-color: #ffffff;
  .left{

  }
  .right{

  }
}
.createOrderDialog{
  color: #666666;
  font-size: 14px;
  .title {
    .foot-tips{
      color: #FC6347;
    }
  }
  .item{
    margin: 30px 0;
    p{
      margin: 3px 0;
      color: #999999;
    }
  }
}
.font-red{
  color: #FF0000;
}
.fenxiao-tips{
  /deep/ .el-dialog__body{
    padding-bottom: 10px;
    padding-top: 0;
  }
}
</style>
